// components/me/me.js

import url from "../../util/url.js"

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    userId:'',
    shareUser: null
  },

  lifetimes: {
    attached: function () {
      this.updateUserInfo()
      wx.getStorage({
       key:'shareUser',
       success:(res) => {
         this.setData({
           shareUser: res.data
         })
       },
     })
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    openShare: function (e) {
      wx.navigateTo({
        url: '/pages/share/share'
      })
    },
    openApply: function (e) {
      wx.navigateTo({
        url: '/pages/apply/apply'
      })
    },
    goLogin: function (e) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
    },
    updateUserInfo:function(){
      wx.getStorage({
        key: 'userId',
        success: (res) => {
          this.setData({
            userId: res.data
          })
        }
      })
    },

    logout:function(e){
      this.setData({
        userId:'',
      })
      wx.clearStorageSync()
      this.triggerEvent("login")
    },

    login:function(e){
      wx.showLoading({
        title: '登录中',
        mask:true
      })
      wx.login({
        success: (res) => {
          if (res.code) {
            //发起网络请求
            console.log('发起登录')
            wx.request({
              url: url.login,
              data: {
                code: res.code,
                userId:this.data.shareUser
              },
              success: (res) => {
                wx.hideLoading()
                console.log(res)
                wx.showModal({
                  title:'提示',
                  content: res.data.msg ? res.data.msg : "登录失败\n错误码" + res.statusCode,
                  showCancel:false
                })
                if (res.data.data && res.data.data.userId){
                  wx.setStorageSync('userId', res.data.data.userId)
                  wx.setStorageSync('openId', res.data.data.openId)
                  this.triggerEvent("login")
                }
              },
              fail:() => {
                wx.hideLoading()
              }
            })
          } else {
            wx.hideLoading()
          }
        },
        fail:() =>{
          wx.hideLoading()
        }
      })
    },

    getPhoneNumber:function(e){
      // e.detail.encryptedData
      // e.detail.iv
    }

  }
})
